package com.eairlv.utils.access;

import com.alibaba.fastjson.JSON;
import com.eairlv.utils.MSInterceptorProperties;
import com.eairlv.utils.annotation.AccessUser;
import com.eairlv.utils.config.MSInterceptor;
import com.eairlv.utils.utils.BeanUtil;
import com.eairlv.utils.validator.user.UserInformation;
import com.eairlv.utils.validator.user.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author eairlv
 * @description
 * @date 13:48 2019/4/28
 */
@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    MSInterceptorProperties msInterceptorProperties;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        AccessUser methodAnnotation = parameter.getMethodAnnotation(AccessUser.class);
        return methodAnnotation != null && methodAnnotation.user() && parameter.getParameterType().isAssignableFrom(UserInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        UserInformation userInformation;
        if (msInterceptorProperties.getUserPayload().equals(UserValidator.HEADER)){
            userInformation = JSON.parseObject(webRequest.getHeader(UserValidator.USER_INFORMATION), UserInformation.class);
        } else {
            userInformation = MSInterceptor.USER_INFORMATION.get();
        }
        UserInfo userInfo = BeanUtil.copyProperties(userInformation, UserInfo.class);
        userInfo.setTime(System.currentTimeMillis());
        return userInfo;
    }
}
